import { useUserInfo } from '@/store/userStore.ts';
import fileServices from '@/api/services/fileServices.ts';
import { useQuery } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import { OSSDataType } from '#/entity.ts';
import { UploadProps } from 'antd';
import { UploadImageProps } from '@/components/UploadImage';
import { useCatch } from '@/hooks';

export const useOss = ({ value, onChange }: UploadImageProps) => {
  const catchFn = useCatch();
  const { realName } = useUserInfo();
  const OSSUrl = 'https://oss.uconcern.com/';

  const [OSSData, setOSSData] = useState<OSSDataType>();
  const { data, refetch } = useQuery({
    queryKey: ['ossToken'],
    queryFn: () => catchFn(() => fileServices.getOssToken()),
    select: ({ data }) => data,
    staleTime: 0,
  });

  useEffect(() => {
    if (data) {
      setOSSData(data);
    }
  }, [data]);

  const handleChange: UploadProps['onChange'] = ({ fileList }) => {
    fileList.map((file) => (file.thumbUrl = file.url));
    onChange?.([...fileList]);
  };

  const beforeUpload: UploadProps['beforeUpload'] = async (file) => {
    if (!OSSData) return false;

    const expire = Number(OSSData.expire) * 1000;

    if (expire < Date.now()) {
      await refetch();
    }

    return file;
  };

  const getExtraData: UploadProps['data'] = (file) => {
    const suffix = file.name.slice(file.name.lastIndexOf('.'));
    const filename = `${Date.now()}${suffix}`;
    const result = {
      key: `${OSSData!.dir}/${realName}/${filename}`,
      OSSAccessKeyId: OSSData?.accessId,
      policy: OSSData?.policy,
      Signature: OSSData?.signature,
    };
    file.url = OSSUrl + result.key;
    return result;
  };

  const uploadProps: UploadProps = {
    fileList: value ?? [],
    action: OSSData?.host,
    data: getExtraData,
    beforeUpload,
    onChange: handleChange,
  };

  return uploadProps;
};
